package com.ccx.demo.open.common.controller;

import com.alibaba.fastjson.JSON;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.support.mvc.entity.IUser;
import com.support.mvc.entity.base.Item;
import com.support.mvc.entity.base.Page;
import com.support.mvc.entity.base.Result;
import com.utils.enums.Code;
import com.utils.util.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Set;
import java.util.concurrent.ExecutorService;

/**
 * 测试接口
 *
 * @author 谢长春 on 2017-9-18
 */
@Api(tags = "0.0.0")
@RequestMapping("/open/test")
@Controller
@Slf4j
@RequiredArgsConstructor
public class OpenTestController {

    private final ExecutorService multiThread;

//    @ApiIgnore
//    @GetMapping("/thymeleaf")
//    public String thymeleaf(ModelMap model) {
//        model.addAttribute("id", Util.uuid32());
//        model.addAttribute("name", "JX");
//        model.addAttribute("zh", "谢");
//        model.addAttribute("timestamp", Dates.now().formatDateTime());
//        return "/static/thymeleaf";
//    }

    @PostMapping
    @ApiOperation(value = "2.测试 POST 保存：返回传入的参数", tags = {"0.0.0"})
    @ApiImplicitParam(name = "body", dataType = "Item", dataTypeClass = Item.class, required = true)
    @ApiOperationSupport(order = 2, author = "谢长春", ignoreParameters = {"body.checked", "body.order.direction", "body.childs[0].order", "body.childs[0].childs"})
    @ResponseBody
    public Result<Item> save(@ApiIgnore @AuthenticationPrincipal final IUser user, @RequestBody(required = false) final String body) {
        return new Result<Item>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setSuccess(JSON.parseObject(body, Item.class))
                .setExtras(JSON.parseObject(body))
        );
    }

    @PutMapping("/{id}")
    @ApiOperation(value = "3.测试 PUT 全量更新", tags = {"0.0.0"})
    @ApiImplicitParam(name = "body", dataType = "Item", dataTypeClass = Item.class, required = true)
    @ApiOperationSupport(order = 3, author = "谢长春", ignoreParameters = {"body.checked", "body.childs"})
    @ResponseBody
    public Result<Void> update(@ApiIgnore @AuthenticationPrincipal final IUser user,
                               @ApiParam(required = true, value = "数据id", example = "1") @PathVariable final String id, @RequestBody(required = false) final String body) {
        return new Result<Void>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setExtras(JSON.parseObject(body))
        );
    }

    @PatchMapping("/change/{id}")
    @ApiOperation(value = "4.测试 PATCH 部分更新", tags = {"0.0.0"})
    @ApiImplicitParam(name = "body", dataType = "Item", dataTypeClass = Item.class, required = true)
    @ApiOperationSupport(order = 4, author = "谢长春")
    @ResponseBody
    public Result<Void> change(@ApiIgnore @AuthenticationPrincipal final IUser user,

                               @ApiParam(required = true, value = "数据id", example = "1") @PathVariable final String id,
                               @RequestBody final String body
    ) {
        return update(user, id, body);
    }

    @DeleteMapping("/{id}")
    @ApiOperation(value = "5.测试 DELETE 按ID 删除", tags = {"0.0.0"})
    @ApiOperationSupport(order = 5, author = "谢长春")
    @ResponseBody
    public Result<Void> deleteById(@ApiIgnore @AuthenticationPrincipal final IUser user,
                                   @ApiParam(required = true, value = "数据id", example = "1") @PathVariable final String id) {
        return new Result<Void>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
        );
    }

    @PatchMapping("/{id}")
    @ApiOperation(value = "6.测试 PATCH 逻辑删除", tags = {"0.0.0"})
    @ApiOperationSupport(order = 6, author = "谢长春")
    @ResponseBody
    public Result<Void> markDeleteById(@ApiIgnore @AuthenticationPrincipal final IUser user,
                                       @ApiParam(required = true, value = "数据id", example = "1") @PathVariable final String id) {
        return new Result<Void>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
        );
    }

    @PatchMapping
    @ApiOperation(value = "7.测试 PATCH 批量逻辑删除", tags = {"0.0.0"})
    @ApiOperationSupport(order = 7, author = "谢长春")
    @ResponseBody
    public Result<Void> markDeleteByIds(@ApiIgnore @AuthenticationPrincipal final IUser user, final Set<String> body) {
        return new Result<Void>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
        );
    }

    @GetMapping("/{id}")
    @ApiOperation(value = "8.测试 GET 按 id 查询单条记录：返回传入的参数", tags = {"0.0.0"})
    @ApiOperationSupport(order = 8, author = "谢长春")
    @ResponseBody
    public Result<Item> findById(@ApiIgnore @AuthenticationPrincipal final IUser user,
                                 @ApiParam(required = true, value = "数据id", example = "1") @PathVariable final String id) {
        return new Result<Item>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setExtras(Maps.ofSS().put("id", id).buildJSONObject())
        );
    }

    @GetMapping
    @ApiOperation(value = "9.测试 GET 查询多条记录：返回传入的参数", tags = {"0.0.0"})
    @ApiOperationSupport(order = 9, author = "谢长春")
    @ResponseBody
    public Result<Item> list(@ApiIgnore @AuthenticationPrincipal final IUser user, final Item json) {
        return new Result<Item>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setSuccess(json)
                .setExtras(JSON.parseObject(JSON.toJSONString(json)))
        );
    }

    @GetMapping("/{number}/{limit}")
    @ApiOperation(value = "10.测试 GET 分页查询：返回传入的参数", tags = {"0.0.0"})
    @ApiOperationSupport(order = 10, author = "谢长春")
    @ResponseBody
    public Result<Item> page(@ApiIgnore @AuthenticationPrincipal final IUser user,
                             @ApiParam(required = true, value = "页码", example = "1") @PathVariable final int number,
                             @ApiParam(required = true, value = "每页条数，最大值1000", example = "10") @PathVariable final int limit,
                             final Item json) {
        return new Result<Item>().execute(result -> result
                .setCode(Code.A00000) // 调用 setSuccess 时不需要设置 code 为 SUCCESS
                .setSuccess(json)
                .setExtras(JSON.parseObject(JSON.toJSONString(Page.builder().number(number).limit(limit).build())))
        );
    }

    @GetMapping(value = "/application/xml", produces = {"application/xml"})
    @ApiOperation(value = "11.测试返回 xml-1", tags = {"0.0.0"})
    @ApiOperationSupport(order = 11, author = "谢长春")
    @ResponseBody
    public String getApplicationXml() {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header>表头</header><body><row><cell>第一列</cell><cell>第二列</cell></row><row><cell>第一列</cell><cell>第二列</cell></row></body></table>";
    }

    @GetMapping(value = "/text/xml", produces = {"text/xml"})
    @ApiOperation(value = "12.测试返回 xml-2", tags = {"0.0.0"})
    @ApiOperationSupport(order = 12, author = "谢长春")
    @ResponseBody
    public String getTextXml(@ApiIgnore @AuthenticationPrincipal IUser user) {
        log.info("{}", user.fillUserByToken());
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><table><header><cell>第一列</cell><cell>第二列</cell></header><body><row><cell>第一行-第一列</cell><cell>第一行-第二列</cell></row><row><cell>第二行-第一列</cell><cell>第二行-第二列</cell></row></body></table>";
    }

//    private UserRepository userRepository;
//
//    @PreAuthorize("hasRole('ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public List<TabUser> getUsers(){
//        return userRepository.findAll();
//    }
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ADMIN')")
//    @GetMapping("/{id}")
//    @ResponseBody
//    public TabUser getUser(@PathVariable String id){
//        return userRepository.findById(id).orElse(null);
//    }
//
//    @PostAuthorize("returnObject.username == principal.username or hasRole('ROLE_ADMIN')")
//    @GetMapping
//    @ResponseBody
//    public TabUser findByUsername(@RequestParam(value = "username") String username){
//        return userRepository.findByUsernameOrPhone(username,username);
//    }

}
